import { defineStore } from "pinia";

//引入接口
import { reqLogin, reqUserInfo, getAuthMenuList } from "@/api/user";
//引入类型
import type { loginFormData } from "@/api/user/type";
import type { UserState } from "./types/type";
//引入操作本地存储的工具方法
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from "@/utils/token";
import { constantRoute, asnycRoute, anyRoute } from "@/router/routes";
const useUserStore = defineStore("user", {
  state: (): UserState => {
    return {
      //   token: localStorage.getItem("TOKEN"),
      token: GET_TOKEN(), //用户唯一标识token
      menuRoutes: [], //仓库存储生成菜单需要数组(路由)
      username: "",
      avatar: "",
      //存储当前用户是否包含某一个按钮
      buttons: [],
      routesLoaded: false,
    };
  },
  actions: {
    async userLogin(data: loginFormData) {
      // 登录
      let res: any = await reqLogin(data);
      if (res.code == 200) {
        this.token = res.data.token; //将token存储到state中
        //将token存储到本地
        SET_TOKEN(res.data.token);
        return "ok";
      } else {
        // return Promise.resolve(res.data.message);
        throw new Error(res.data.message);
      }
    },
    // 获取用户信息的方法
    async userInfo() {
      let res = await reqUserInfo();
      let res2 = await getAuthMenuList();
      console.log("路由情况", res2);
      console.log("用户信息：", res);
      if (res.code == 200) {
        this.username = res.data.checkUser.username;
        this.avatar = res.data.checkUser.avatar;
        this.buttons = res.data.buttons;

        // 根据权限过滤异步路由
        // const filteredRoutes = this.filterAsyncRoutes(asnycRoute, buttons);
        // 将过滤后的异步路由添加到菜单路由中
        this.menuRoutes = [...constantRoute];
      } else {
      }
    },

    //
    userLogout() {
      (this.token = ""), (this.username = ""), (this.avatar = "");
      REMOVE_TOKEN();
    },
    // 根据用户权限过滤异步路由
    // filterAsyncRoutes(routes, permissions) {
    //   return routes.filter((route) => {
    //     // 检查是否有权限访问该路由
    //     if (route.meta?.permissions) {
    //       return permissions.includes(route.meta.permissions);
    //     }
    //     if (route.children && route.children.length) {
    //       route.children = this.filterAsyncRoutes(route.children, permissions);
    //       return route.children.length > 0;
    //     }
    //     return true;
    //   });
    // },
  },
  getters: {},
});

export default useUserStore;
